package com.itheima.app.usermanager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.autoconfig.face.AipFaceTemplate;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.Log;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.service.UserInfoService;
import com.itheima.service.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserManager {
    @DubboReference
    private UserService userService;
    @DubboReference
    private UserInfoService userInfoService;
    //注入rabbitMQ
    @Autowired
    private RabbitTemplate rabbitTemplate;
    //注入stringrad
    @Autowired
    private StringRedisTemplate redisTemplate;
    //注入阿里云图片上传
    @Autowired
    private OssTemplate ossTemplate;
    //注入人脸识别
    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    //调用添加方法
    //responseentity 作用是当程序运行出错的时候会捕获异常，并且返回给前端自定义的数据！
    public Long save(User user){
        return userService.sava(user);
    }
    //根据手机号查询
    public ResponseEntity findByPhone(String phone){
        //try {
        //    int a = 1 / 0;
        //} catch (Exception e) {
        //    e.printStackTrace();
        //    return ResponseEntity.status(500).body(ErrorResult.error());
        //}
        return ResponseEntity.ok(userService.findByPhone(phone));
    }

    public void sendSms(String phone) {
        //获得随机的六位数
        String sms = RandomUtil.randomNumbers(6);
        sms ="123456";
        //将验证码存入redis中
        redisTemplate.opsForValue().set(ConstantUtil.SMS_CODE+phone,sms, Duration.ofMinutes(5));

    }
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    // 注册、登录功能
    public ResponseEntity loginAndRegister(String phone, String verificationCode) {
        // 声明一个返回将结果
        Map<String, Object> resultMap = new HashMap<>();

        // 1.获取redis中验证码
        String codeFromRedis = redisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        // 2.对比验证码是否一致
        if (!StrUtil.equals(verificationCode, codeFromRedis)) {
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
         String tepy = null;
        // 3.根据手机号查询用户
        User user = userService.findByPhone(phone);
        if (user != null) { // 老用户
            resultMap.put("isNew", false);
            tepy ="0101";
        } else {// 新用户
            resultMap.put("isNew", true);
            tepy = "0102";
            // 帮新用户注册
            user = new User();
            user.setPhone(phone);
            user.setPassword(ConstantUtil.INIT_PASSWORD);
            Long newUserId = userService.sava(user);
            user.setId(newUserId);
            huanXinTemplate.register("HX"+newUserId);

        }
        // 4.使用jwt制作令牌
        user.setPassword(null);
        Map<String, Object> claims = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(claims);
        // 5.redis存储用户信息
        String json = JSON.toJSONString(user);
        redisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(7));

        // 清除短信验证码
        redisTemplate.delete(ConstantUtil.SMS_CODE + phone);

        // 6.返回结果
        resultMap.put("token", token);
        //7 发送日志消息
        Log log = new Log();
        log.setUserId(user.getId());
        log.setLogTime(DateUtil.formatDate(new Date()));
        log.setPlace("北京顺义");
        log.setEquipment("国产小辣椒");
        log.setType(tepy);
        rabbitTemplate.convertAndSend("tanhua.log", log);

        return ResponseEntity.ok(resultMap);
    }
     //用户信息完善
    public void saveUser(UserInfo userInfo, String token) {
        // 1.解析token获取user对象
        User user = findUserByToken(token);
        //将user对象的id给userinfo
        userInfo.setId(user.getId());
        userInfoService.save(userInfo);

    }
    //解析token

    public User findUserByToken(String token) {
        // 1.对token进行非空判断
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        // 2.获取redis中user对象
        String json = redisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);

        // 3.对json进行非空判断
        if (StrUtil.isEmpty(json)) {
            return null;
        }

        // 4.转换为user对象
        User user = JSON.parseObject(json, User.class);

        // 5.对redis的user进行续期
        redisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(7));

        return user;
    }
//头像上传
    public ResponseEntity update(MultipartFile headPhoto, String token) throws IOException {
        //识别令牌
        User user = findUserByToken(token);
        //判断图片是否合格
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        System.err.println("---------------------------------------------------------------------------------------------------------"+detect);

        if (detect==false){
            //如果不合格，给前端报错
            System.err.println("---------------------------------------------------------------------------------------------------------"+detect);
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }
        //如果合格,将图片上传至oss
        String uil = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //定义一个userinfo类，然后将图片上传！
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId()); // 用户id
        userInfo.setAvatar(uil); // 头像
        userInfo.setCoverPic(uil); // 背景
        //远程调用，修改userinfo
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);


    }

    public ResponseEntity findUserInfoVo(Long id) {
       UserInfo userInfo= userInfoService.select(id);
        // 2.封装userInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo, userInfoVo);
        // 3.返回
        return ResponseEntity.ok(userInfoVo);


    }

    public void updateUserInfoBase(UserInfo userInfo, String token) {
        User user = findUserByToken(token);
        userInfo.setId(user.getId());
        // 3.调用rpc完成更新
        userInfoService.update(userInfo);
    }
}
